import 'package:get/get.dart';
import '../model/single_chat_message_model.dart';
import '../data/single_chat_message_data.dart';

/// 单聊消息状态管理（文本消息 + 已读未读）
class SingleChatMessageState extends GetxController {
  // 所有消息
  final RxList<SingleChatMessageModel> _allMessages =
      <SingleChatMessageModel>[].obs;

  // 当前用户ID（默认admin: '1'）
  final RxString _currentUserId = '1'.obs;

  /// 获取所有消息
  List<SingleChatMessageModel> get allMessages => _allMessages.toList();

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
    update();
  }

  /// 获取某个聊天的消息（按时间升序）
  List<SingleChatMessageModel> getMessagesByChatId(String chatId) {
    return _allMessages.where((m) => m.chatId == chatId).toList()
      ..sort((a, b) => a.sendTime.compareTo(b.sendTime));
  }

  /// 发送文本消息
  SingleChatMessageModel sendTextMessage({
    required String chatId,
    required String content,
  }) {
    final message = SingleChatMessageModel(
      id: 'msg_${DateTime.now().millisecondsSinceEpoch}',
      chatId: chatId,
      senderId: _currentUserId.value,
      content: content,
      sendTime: DateTime.now(),
      isRead: false,
    );
    _allMessages.add(message);
    update();
    return message;
  }

  /// 标记某聊天内他人发送的消息为已读
  void markChatMessagesAsRead(String chatId) {
    bool changed = false;
    for (int i = 0; i < _allMessages.length; i++) {
      final m = _allMessages[i];
      if (m.chatId == chatId &&
          m.senderId != _currentUserId.value &&
          !m.isRead) {
        _allMessages[i] = m.markAsRead();
        changed = true;
      }
    }
    if (changed) {
      _allMessages.refresh();
      update();
    }
  }

  /// 计算某聊天的未读消息数量
  int getChatUnreadCount(String chatId) {
    return _allMessages
        .where(
          (m) =>
              m.chatId == chatId &&
              m.senderId != _currentUserId.value &&
              !m.isRead,
        )
        .length;
  }

  /// 计算全部未读消息数量
  int get totalUnreadCount {
    return _allMessages
        .where((m) => m.senderId != _currentUserId.value && !m.isRead)
        .length;
  }

  /// 删除某条消息
  void removeMessage(String messageId) {
    _allMessages.removeWhere((m) => m.id == messageId);
    update();
  }

  /// 清空某个聊天的所有消息
  void clearChatMessages(String chatId) {
    _allMessages.removeWhere((m) => m.chatId == chatId);
    update();
  }

  /// 清空
  void clearAllMessages() {
    _allMessages.clear();
    update();
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  void _loadDefaultData() {
    _allMessages.assignAll(
      SingleChatMessageData.getDefaultSingleChatMessages(),
    );
  }
}
